//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package data_anno_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/data_anno_project_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ResourceInfoDbItem struct {
	ResourceId    string `bson:"_id"`
	AnnoProjectId string `bson:"annoProjectId"`
	Content       string `bson:"content"`
	StoreAsFile   bool   `bson:"storeAsFile"`
	TaskCount     uint32 `bson:"taskCount"`
	TimeStamp     int64  `bson:"timeStamp"`
}

func (item *ResourceInfoDbItem) ToResourceInfo() *data_anno_project_api.ResourceInfo {
	return &data_anno_project_api.ResourceInfo{
		ResourceId:    item.ResourceId,
		AnnoProjectId: item.AnnoProjectId,
		Content:       item.Content,
		StoreAsFile:   item.StoreAsFile,
		TaskCount:     item.TaskCount,
	}
}

type _ResourceDao struct {
	mc *mongo.Collection
}

func newResourceDao(db *mongo.Database) (*_ResourceDao, error) {
	mc := db.Collection(db_ns.DB_NS_DATA_ANNO + "resource")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"annoProjectId", 1}, {"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ResourceDao{mc: mc}, nil
}

func (db *_ResourceDao) Insert(ctx context.Context, dbItem *ResourceInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ResourceDao) Remove(ctx context.Context, resourceId, annoProjectId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": resourceId, "annoProjectId": annoProjectId})
	return err
}

func (db *_ResourceDao) RemoveByAnnoProject(ctx context.Context, annoProjectId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"annoProjectId": annoProjectId})
	return err
}

func (db *_ResourceDao) Exist(ctx context.Context, resourceId, annoProjectId string) (bool, error) {
	query := bson.M{"_id": resourceId}
	if annoProjectId != "" {
		query["annoProjectId"] = annoProjectId
	}
	count, err := db.mc.CountDocuments(ctx, query)
	return count > 0, err
}

func (db *_ResourceDao) Get(ctx context.Context, resourceId, annoProjectId string) (*ResourceInfoDbItem, error) {
	query := bson.M{"_id": resourceId}
	if annoProjectId != "" {
		query["annoProjectId"] = annoProjectId
	}
	retItem := &ResourceInfoDbItem{}
	err := db.mc.FindOne(ctx, query).Decode(retItem)
	return retItem, err
}

func (db *_ResourceDao) Count(ctx context.Context, annoProjectId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"annoProjectId": annoProjectId})
	return uint32(count), err
}

func (db *_ResourceDao) List(ctx context.Context, annoProjectId string, offset, limit int64) ([]*ResourceInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"annoProjectId": annoProjectId}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*ResourceInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ResourceDao) DistinctResourceIdByProject(ctx context.Context, annoProjectIdList []string) ([]string, error) {
	itemList, err := db.mc.Distinct(ctx, "_id", bson.M{"annoProjectId": bson.M{"$in": annoProjectIdList}})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range itemList {
		retList = append(retList, item.(string))
	}
	return retList, nil
}

func (db *_ResourceDao) ListByTaskCount(ctx context.Context, annoProjectId string) ([]*ResourceInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"annoProjectId": annoProjectId}, options.Find().SetSort(bson.M{"taskCount": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*ResourceInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ResourceDao) UpdateTaskCount(ctx context.Context, resourceId, annoProjectId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": resourceId, "annoProjectId": annoProjectId}, bson.M{"$set": bson.M{"taskCount": count}})
	return err
}

func (db *_ResourceDao) ListById(ctx context.Context, annoProjectId string, resourceIdList []string) ([]*ResourceInfoDbItem, error) {
	if len(resourceIdList) == 0 {
		return []*ResourceInfoDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": resourceIdList}, "annoProjectId": annoProjectId})
	if err != nil {
		return nil, err
	}
	retList := []*ResourceInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
